package current.aqs;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.TimeUnit;

/**
 * CyclicBarrier
 */
public class CyclicBarrierUseDemo2 {

    CyclicBarrier barrier;

    int page = 0;

    public CyclicBarrierUseDemo2() {
        barrier = new CyclicBarrier(2, () -> {
            System.out.println("同步...");
            page++;
            try {
                TimeUnit.MICROSECONDS.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
    }

    void prepareProducts() {
        while (page < 1000) {
            try {
                System.out.println("准备产品...");
                barrier.await();
            } catch (InterruptedException | BrokenBarrierException e) {
                e.printStackTrace();
            }
        }
    }

    void deliveryOrders() {
        while (page < 1000) {
            try {
                System.out.println("发货...");
                barrier.await();
            } catch (InterruptedException | BrokenBarrierException e) {
                e.printStackTrace();
            }
        }
    }

    void run() {
        new Thread(this::prepareProducts).start();
        new Thread(this::deliveryOrders).start();
    }

    public static void main(String[] args) {
        CyclicBarrierUseDemo2 test = new CyclicBarrierUseDemo2();
        test.run();
    }
}
